import { Injectable, Inject } from '@nestjs/common';
import { createTransport, Transporter } from 'nodemailer';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class EmailService {
  private transporter: Transporter;

  // 相当于机器代替你写邮件，只需要授权它代表你就行了
  constructor(private readonly config: ConfigService) {
    this.transporter = createTransport({
      host: this.config.get<string>('email.host'),
      port: this.config.get<number>('email.port'),
      secure: false, // true for 465, false for other ports
      auth: {
        user: this.config.get<string>('email.user'),
        pass: this.config.get<string>('email.pass'),
      },
    });
  }
  async sendMail({ to, subject, html }) {
    await this.transporter.sendMail({
      // 来信人信息
      from: {
        name: this.config.get<string>('email.name') || '聊天室',
        address: this.config.get<string>('email.user'),
      },
      // 收信人信息
      to,
      // 邮件主题
      subject,
      // 邮件内容
      html,
    });
  }
}
